#include <iostream>
#include <thread>
#include <mysql/mysql.h>

int main(){

    MYSQL mysql;
    mysql_init(&mysql);
    const char* host = "127.0.0.1";
    const char* user = "root";
    const char* pass = "123456";
    const char* db = "mysql";

    //连接超时
    int to = 3;
    int re = mysql_options(&mysql,MYSQL_OPT_CONNECT_TIMEOUT,&to);
    if(re != 0){
        std::cerr<<"mysql_options failed!"<<mysql_error(&mysql)<<std::endl;
    }

    //自动重连
    int reconnect = 3;
    mysql_options(&mysql,MYSQL_OPT_RECONNECT,&reconnect);

    //连接（阻塞的）
    if(!mysql_real_connect(&mysql,host,user,pass,db,3306,0,0)){
        std::cerr<<"mysql connect failed!"<<mysql_error(&mysql)<<std::endl;
    }else{
        std::cout<<"mysql connect "<<host<<" success!"<<std::endl;
    }

    //测试
    for(int i = 0;i<1000;i++){
        int re = mysql_ping(&mysql);
        if(re == 0){
            std::cout<<"mysql_ping "<<host<<" success!"<<std::endl;
        }else{
            std::cerr<<"mysql_ping failed!"<<mysql_error(&mysql)<<std::endl;
        }
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }


    mysql_close(&mysql);
    return 0;
}